package com.wallace.downloadserver.controller

import com.wallace.downloadserver.annotation.ForbidMultipleCalls
import com.wallace.downloadserver.myconst.DefineName
import com.wallace.downloadserver.myconst.ResponseMessage
import com.wallace.downloadserver.template.ResponseTemplate
import com.wallace.downloadserver.util.HttpUtil
import com.wallace.downloadserver.util.myEncrypt.RSAUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import java.util.*
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest

@RestController
@RequestMapping(value = ["/downloadserver/api/preRequest"], produces = ["application/json; charset=utf-8"])
class PreRequestController {

    private val log: Logger = LoggerFactory.getLogger(PreRequestController::class.java)

    @ForbidMultipleCalls(interval = 1000L, maxCount = 5)
    @RequestMapping(value = ["/preRequest"], method = [RequestMethod.GET])
    fun preRequest(request: HttpServletRequest): ResponseTemplate {
        val host = HttpUtil.getRealIp(request)
        val localAddr = request.localAddr
        val localPort = request.localPort
        val session = request.getSession(true)
        // 创建RSA密钥对，返回公钥给客户端
        val rsaKeys = RSAUtil.createKeys()
        val encoder = Base64.getEncoder()
        val publicKeyString = encoder.encode(rsaKeys.getPublicKey()).toString(Charsets.UTF_8)
        val privateKeyString = encoder.encode(rsaKeys.getPrivateKey()).toString(Charsets.UTF_8)
        session.setAttribute(DefineName.RSA_PRIVATE_KEY, privateKeyString)
        // 一分钟内必须登录
        session.maxInactiveInterval = TimeUnit.SECONDS.toSeconds(60L).toInt()
        val action = "服务端[$localAddr:$localPort]为客户端[$host]新建session[ID:${session.id}]"
        log.info(action)
        return ResponseTemplate(ResponseMessage.Success.PUBLIC_KEY_CREATED, publicKeyString)
    }
}